package com.joker.aigc.accountboolk.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.joker.aigc.accountboolk.domain.dto.AiEntityDTO;
import com.joker.aigc.accountboolk.domain.vo.AccountBookVO;
import com.joker.aigc.accountboolk.domain.vo.ResultVO;
import com.joker.aigc.accountboolk.service.AiService;
import com.joker.aigc.accountboolk.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @description:
 * @author: feixiang.li
 * @date: 2025-01-07 18:02
 */
@Slf4j
@Service
public class AiServiceImpl implements AiService {


    @Value("${apikey}")
    private String apiKey;

//    @Resource
//    private FeignService feignService;


    public GenerationParam getParam(List<Message> messages) {
        return GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                .model("qwen-plus")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
    }

    @Override
    public List<AccountBookVO> convert(MultipartFile file) {
        AiEntityDTO aiEntityDTO = new AiEntityDTO();

        aiEntityDTO.setFile(file);
        // 看一下程序运行时间
        StopWatch stopWatch = new StopWatch("MyStopWatch");
        stopWatch.start("task1: 调用翻译引擎");
//        String json = feignService.encoder(aiEntityDTO);
//        log.info("json: {}", json);
//        ResultVO<String> stringResultVO = JSON.parseObject(json, new TypeReference<ResultVO<String>>() {
//        });
        ResultVO<String> stringResultVO = new ResultVO<>();
        log.info("stringResultVO: {}", stringResultVO);
        stopWatch.stop();
        stopWatch.start("task2: 调用ai引擎");
        Generation gen = new Generation();
        String today = DateUtil.today();
        String content = "你现在是一个记账系统，需要根据用户的文字，输出固定格式内容的json数组，格式如下[{\n" +
                "  \"type\":1,\n" +
                "  \"name\":\"\",\n" +
                "  \"amount\": 0.0,\n" +
                "  \"category\": \"\",\n" +
                "  \"date\": \"\"\n" +
                "}] type 账本类型 1-收入 2-支出 name表示 账单名称，如早饭，amount表示金额，category表示 账单分类，比如餐饮，其他，date格式为yyyy-mm-dd格式，今天的日期为" + today;
        log.info(content);
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content(content)
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(stringResultVO.getData())
                .build();

        GenerationParam param = getParam(Arrays.asList(systemMsg, userMsg));
        try {
            GenerationResult call = gen.call(param);
            log.info("call result: {}", call);
            GenerationOutput.Choice choice = call.getOutput().getChoices().get(0);
            String content1 = choice.getMessage().getContent();
            log.info(content1);
            stopWatch.stop();
            stopWatch.shortSummary();
            // 任务总的耗时  如果你想获取到每个任务详情（包括它的任务名、耗时等等）可使用
            log.info("所有任务总耗时（毫秒）：" + stopWatch.getTotalTimeMillis());
            List<AccountBookVO> jsonArray = JsonUtils.getJsonArray(content1, AccountBookVO.class);
            log.info("解析出来的数据为: {}", jsonArray);
            return jsonArray;
        } catch (NoApiKeyException e) {
            log.error("没有配置apiKey", e);
        } catch (InputRequiredException e) {
            log.error("参数错误", e);
        }
        return Collections.emptyList();
    }
}
